package top.hzy520.email.service;

import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.hzy520.common.constants.Constants;
import top.hzy520.common.exception.YuYuBuyException;
import top.hzy520.common.util.RandomNumber;
import top.hzy520.common.util.RedisUtil;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 14:19 2018/5/30
 */
@Slf4j
@Service
public class QqEmailServiceImpl implements QqEmailService {
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public void sendEmailToQueue(String email, String code) {
        try {
            Date date=new Date();
            DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Properties props = new Properties();
            String time=format.format(date);
            // 开启debug调试
            props.setProperty("mail.debug", "true");
            // 发送服务器需要身份验证
            props.setProperty("mail.smtp.auth", "true");
            // 设置邮件服务器主机名
            props.setProperty("mail.host", "smtp.qq.com");
            // 发送邮件协议名称
            props.setProperty("mail.transport.protocol", "smtp");

            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);

            Session session = Session.getInstance(props);
            // 填写要发送的消息
            Message msg = new MimeMessage(session);
            msg.setSubject(Constants.EMAIL_TITLE);
            StringBuilder builder = new StringBuilder();
            builder.append(email+","+"您好!\n");
            builder.append("为确保是您本人操作，请在邮件验证码输入框输入下方验证码：\n");
            builder.append(code+"\n");
            builder.append("请勿向任何人泄露您收到的验证码。\n");
            builder.append("\n时间 "+time);
            msg.setText(builder.toString());
            msg.setFrom(new InternetAddress("1067325672@qq.com"));

            Transport transport = session.getTransport();
            transport.connect("smtp.qq.com", "1067325672@qq.com", "swciwjzpnzalbcfg");
            transport.sendMessage(msg, new Address[] { new InternetAddress(email) });
            transport.close();
            redisUtil.setEmailVerifyCode(email,code,60);
        } catch (Exception e) {
            log.error(email+": 用户发送邮箱异常",e);
            throw new YuYuBuyException("发送邮箱验证码异常");
        }
    }
}
